package dao

import (
	"Wechat/Tools"
	"Wechat/domain"
	"errors"
	"gorm.io/gorm"
	"time"
)

// 创建一个ForumDataMapper类型，用于调用函数
type ForumDataMapper string

// 从数据库连接池中获取一个接口
var forumDB *gorm.DB = Tools.GetDB()

// 插入帖子：返回影响的条数
func (f ForumDataMapper) InsertText(title, unionid, picpath, detail, videopath string, id int) int64 {
	// 创建实体变量存储
	forum := domain.Forum{
		Title:     title,
		PicPath:   picpath,
		Detail:    detail,
		Time:      time.Now(),
		UnionID:   unionid,
		VideoPath: videopath,
		ID:        id,
	}
	//	插入指定字段的值
	result := forumDB.Select("forumTitle", "forumPicPath", "forumVideoPath", "forumID", "forumUnionID", "forumDetail", "forumTime").Create(&forum)
	Tools.CherrError(result.Error, "Insert forum ERROR!")
	return result.RowsAffected
}

// 添加评论，forumID为第几条评论，commentID为对应帖子的ID
func (f ForumDataMapper) InsertComment(detail, unionid string, forumid int) int64 {
	//	创建实体变量存储
	forum := domain.Forum{
		Detail:    detail,
		UnionID:   unionid,
		ID:        -1,
		Time:      time.Now(),
		CommentID: forumid,
	}
	//	插入
	result := forumDB.Select("forumTitle", "forumDetail", "forumUnionID", "forumID", "forumTime", "forumCommentID").Create(&forum)
	Tools.CherrError(result.Error, "Insert comment ERROR!")
	return result.RowsAffected
}

// 帖子详情
func (f ForumDataMapper) SelectText(forumID int) domain.Forum {
	forum := domain.Forum{
		ID: forumID,
	}
	//	查询
	result := forumDB.Find(&forum, "forumID = ?", forumID)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return domain.Forum{}
	} else if result.Error != nil {
		Tools.CherrError(result.Error, "Select text ERROR!")
	}
	return forum
}

// 帖子列表
func (f ForumDataMapper) SelectTextList(forumID int) []domain.Forum {
	var forumArr []domain.Forum
	result := forumDB.Limit(10).Order("forumTime DESC").Where("forumID > ?", forumID).Find(&forumArr)
	Tools.CherrError(result.Error, "Select list text ERROR!")
	return forumArr
}

// 评论列表
func (f ForumDataMapper) SelectCommentList(forumID int) []domain.Forum {
	var forumArr []domain.Forum
	result := forumDB.Limit(100).Order("forumTime DESC").Where("forumCommentID = ?", forumID).Find(&forumArr)
	Tools.CherrError(result.Error, "Select list comment ERROR!")
	return forumArr
}

// 获取当前最新帖子的信息
func (f ForumDataMapper) SelectNewText() domain.Forum {
	forum := domain.Forum{}
	result := forumDB.Limit(1).Order("forumTime DESC").Where("forumID <> ? ", -1).Find(&forum)
	Tools.CherrError(result.Error, "Select new text ERROR!")
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return domain.Forum{}
	}
	return forum
}
